package video.hai.vui;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

import video.hai.vui.jsonParse;
import video.hai.vui.R;

import android.support.v4.app.Fragment;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.os.Build;


public class MainActivity extends Activity {	
	private AdView adView;
	private WebView fullContent;
	private ProgressBar Pbar;
	private WebSettings fullContentsettings;
	private AlertDialog.Builder alertDialogBuilder;
	private AlertDialog alertDialog;
	ListView list;
    LazyAdapter adapter;
    private jsonParse jsonP;
    public ArrayList<HashMap<String, String>> itemNewsList;
    private Boolean loading=true;    
    private ProgressDialog dialog;
    private Handler progressBarHandler = new Handler();
    private int progressBarStatus = 0;
    private Thread tPr;
    private String processMessage="Đang tải dữ liệu";
    public String alertMessage="Không kết nối được, một trong các nguyên nhân sau:";
	public String connecMessage="-Kiểm tra lại đường truyền Internet.\r\n-Website đang bảo trì.";
	//private ActionBar actionBar;
	private static final String AD_UNIT_ID = "ca-app-pub-6575239088642506/1558548874";
	private ActionBar actionBar;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		actionBar = getActionBar();
		dialog=new ProgressDialog(this);
		Log.e("onCreateonCreateonCreateonCreate", "ok1");
		//actionBar.setDisplayShowTitleEnabled(false); 
		Log.e("onCreateonCreateonCreateonCreate", "ok2");
		//actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg));
		Log.e("onCreateonCreateonCreateonCreate", "ok3");
		showNewsFromUrl("http://hayhayvuivui.com/Home/getVideoApp?page=1");
		Log.e("onCreateonCreateonCreateonCreate", "ok4");
	}
	private void nextPage(){
		Config.currentPage++;
		if (Config.currentPage>100) Config.currentPage=100;
		if (Config.currentPage<=100){			
			showNewsFromUrl("http://hayhayvuivui.com/Home/getVideoApp?page="+String.valueOf(Config.currentPage));
		}
	}
	private void prePage(){
		Config.currentPage--;
		if (Config.currentPage<=0) Config.currentPage=1;
		if (Config.currentPage<=1){			
			showNewsFromUrl("http://hayhayvuivui.com/Home/getVideoApp?page="+String.valueOf(Config.currentPage));
		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate menu resource file.
		Log.e("onCreateOptionsMenu", "ok1");
		getMenuInflater().inflate(R.menu.menu_main, menu);
		Log.e("onCreateOptionsMenu", "ok2");
		//return true;
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.e("onOptionsItemSelectedonOptionsItemSelected", "ok1");
		switch (item.getItemId()) {
		case R.id.menu_item_next:			
			nextPage();
			return true;
		case R.id.menu_item_pre:
			prePage();
			return true;
		case R.id.menu_item_home:
			showNewsFromUrl("http://hayhayvuivui.com/home/getVideoApp?page=1");
    		return true;
		default:
			return super.onOptionsItemSelected(item);
		}
		//Log.e("onOptionsItemSelectedonOptionsItemSelected", "ok2");
	}
	public void showNewsFromUrl(String url){	

		progressBarStatus=0;
		dialog.setMessage(processMessage);
		dialog.setCancelable(false);
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		dialog.setProgress(0);
		dialog.setMax(100);
		//dialog.setIndeterminate(true);
		dialog.show();

	   final int totalProgressTime = 100;

	   tPr = new Thread(){

	   @Override
	   public void run(){
	 
	      int jumpTime = 0;
	      while(jumpTime < totalProgressTime && progressBarStatus!=-1){
	         try {
	            sleep(1000);
	            jumpTime += 5;
	            progressBarStatus = jumpTime;
	            //dialog.setProgress(jumpTime);
	            // Update the progress bar
				  progressBarHandler.post(new Runnable() {
					public void run() {
						dialog.setProgress(progressBarStatus);
					}
				  });
	         } catch (InterruptedException e) {
	           // TODO Auto-generated catch block
	           e.printStackTrace();
	         }

	      }

	   }
	   };
	   tPr.start();
	   
		//dialog = ProgressDialog.show(LoadingScreenActivity.this,"Loading...","Loading application View, please wait...", false, false); 
		new showNewsFromUrlTask().execute(url);		
		Log.e("showNewsFromUrl", "2");
		    
	}	
	private class showNewsFromUrlTask extends AsyncTask<String, Void, String> {    	
        @Override
        protected String doInBackground(String... urls) {
              
            // params comes from the execute() call: params[0] is the url.
            try {
            	//Log.e("showNewsFromUrlTask", "1");
            	
            	Log.e("showNewsFromUrlTask", "ok1");
        		jsonP=new jsonParse(urls[0]);
        		Log.e("showNewsFromUrlTask", "ok2");
        		//boolean result=
                return jsonP.fetchJSON();
            } catch (Exception e) {
            	//Log.e("showNewsFromUrlTask", "can not download");
            	//tPr.interrupt();
            	//progressBarStatus=-1;
            	//dialog.setProgress(0);
            	//dialog.cancel();
            	//dialog.dismiss();
            	showExtProgram(alertMessage,connecMessage);
            	//ResultDownloadWebpage=0;            	
            	return "0";
            }
        }
        
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        	//try{
        		//if(dialog!=null) 
        	///isSearching=false;
        	tPr.interrupt();
        	progressBarStatus=-1;
        	//dialog.setProgress(0);
        	//dialog.cancel();
   			dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
        	if (result.equals("0")){ 
        		Log.e("onPostExecute", "can not download");
        		showExtProgram(alertMessage,connecMessage);
        	}else{        		
        		Log.e("onPostExecute", "ok");
        		displayNewsContent();
        	}
        	//try{
        		//if(dialog!=null) dialog.dismiss();
        	//}catch(Exception ex){
        		
        	//}
       }
    }
public void showExtProgram(String title,String message){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

    	// 2. Chain together various setter methods to set the dialog characteristics
    	builder.setMessage(message)
    	       .setTitle(title)
    	       .setCancelable(false)
			   .setPositiveButton("Thoát",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity							
						//MainActivity.this.finish();
				    	//System.exit(0);
					}
				 });

    	// 3. Get the AlertDialog from create()
    	alertDialog= builder.create();
    	alertDialog.show();
//    	int duration = Toast.LENGTH_SHORT;	
//		Toast toast = Toast.makeText(context, message, duration);
//		toast.show();
	}
	public void displayNewsContent(){
		itemNewsList = new ArrayList<HashMap<String, String>>();
	    itemNewsList=jsonP.getItemNewsList();
	    //Log.e("itemNewsList", "ok1");	
	    list=(ListView)findViewById(R.id.list);
		////////// Viec customize listview duoc thuc hien o LazayAdapter
        adapter=new LazyAdapter(this, itemNewsList,this.getBaseContext()); 
        int[] colors = {0xCECECECE, 0xCECECECE, 0xCECECECE}; 
        list.setAdapter(adapter);
        list.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
        list.setDividerHeight(10);
        list.setPadding(10,10,10,50);
        list.setBackgroundColor(0xFFFFFFFF);
        //Log.e("list.setAdapter(adapter);", "ok2");
	//}
        list.setOnItemClickListener(new OnItemClickListener() {
        	@Override
        	public void onItemClick(AdapterView<?> parent, View view,
				int position, long id) {
				//String link=String.valueOf(itemNewsList.get(position).get("link"));
				String idNews=String.valueOf(itemNewsList.get(position).get("id"));
				//Log.e("user click","pos="+String.valueOf(position)+",id="+String.valueOf(id)+" "+link);
				//final ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "Diemtinvietnam.vn","Loading...", true);
				//new Thread(new Runnable(){
						//public void run(){
							//try {
									//---simulate doing something lengthy---
									//Thread.sleep(5000);
									//while(jsonP.parsingComplete);
									//---dismiss the dialog---
									//dialog.dismiss();
								//} catch (InterruptedException e) {
									//e.printStackTrace();
								//}
						//}
				//}).start();	
				Log.e("Log","ket thuc loading, bat dau goi View Web");
				Intent vi = new Intent(MainActivity.this, viewWeb.class);
				//Intent vi = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
				//vi.putExtra("link", link);			
				vi.putExtra("id", idNews);
				vi.setData(Uri.parse(idNews));
				startActivity(vi);
				Log.e("Log","ket thuc  goi View Web");
					
			}
		});	
	}

	public void onBackPressed()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

    	// 2. Chain together various setter methods to set the dialog characteristics
    	builder.setMessage("Bạn có muốn thoát chương trình?")    	       
    	       .setCancelable(false)
			   .setPositiveButton("Có",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						
						MainActivity.this.finish();
				    	System.exit(0);
					}
				 }).setNegativeButton("Không",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						
						alertDialog.hide();
					}
				 });

    	// 3. Get the AlertDialog from create()
    	alertDialog= builder.create();
    	alertDialog.show();
		
	}
	

}
